Monitoring Mouse Movement with GetCursorPos
Now that you've seen how to use the API Viewer to work more easily
with the Windows API, let's put the function GetCursorPos to
work in a real-world example.
GetCursorPos reports the position of the mouse pointer anywhere
onscreen. Normally, a Visual Basic application is limited to reporting
the position of the mouse pointer with the boundaries of itself, so
the application has no idea where the cursor is when the mouse pointer
is moved beyond a Visual Basic application's form. However, windows
always knows where the mouse pointer is and reports the location through
the GetCursorPos API function.
The project prjAPIStuff.vbp, which is available with the source text,
illustrates this use of . Within the project, in the module modAPIStuff
is a user-defined function, ReportMousePos(), which returns
a string that reports back the location of the mouse pointer in friendly
language. The function is a wrapper function for GetCursorPos.
A wrapper function is one that primarily uses the functionality of another
function, as if the function were wrapping itself around another. Listing
1 shows the structure of ReportMousePos().
Notice that line 3 initializes POINTAPI. The actual declaration
of the type and the GetCursorPos function were done in the
General Declarations section of the module. Line 8 calls the GetCursorPos
function, using the type instance MyPointAPI as an argument.
Windows passes back the x and y location of the mouse pointer to the
elements of MyPointAPI. If the value of l (the return buffer)
is greater than 0, the call was successful. Lines 11 and 12 concatenate
a string that reports back the pixel location of the mouse pointer with
some "x:" and "y:" labeling. If the operation was
successful (line 15), the reporting string is returned by the ReportMousePos()
function. Otherwise, it returns an error string (line 18).
This function is called from within a Timer control's Timer()
event procedure. The Timer() event procedure assigns the function's
return value to the Caption property of a Label control. The
event procedure is as follows:
Private Sub Timer1_Timer()
lblMousePos.Caption = ReportMousePos()
End Sub
GetCursorPos does not report back the mouse pointer position
unless called. Therefore, the Timer control is used to poll Windows
every 1/10 of a second for the location of the mouse pointer. For more
information about timers, see the source text in Chapter 16: "Working
with Time and Timers."